import {
  getTeamInfoList,
  getEmployeesInfo,
  addTeam,
  updateTeam,
  deleteTeam,
} from "@/api/basicData/teamManagement.js";

export const myMethod = {
  // 切换条数
  handleSizeChange(val) {
    this.pageSize = val;
    this.currentPage = 1;
    this.getTableData();
  },
  // 切换页码
  handleCurrentChange(val) {
    this.currentPage = val;
    this.getTableData();
  },
  // 点击查询操作
  queryChange(val) {
    this.form = Object.assign(this.form, val);
    this.currentPage = 1;
    this.getTableData();
  },
  // 重置查询数据
  resetPage() {
    this.pageSize = 15;
    this.currentPage = 1;
    this.totalPage = 0;
    this.$refs.dataTableRef.tableData = [];
    this.form = {};
  },
  // 获取列表数据
  async getTableData() {
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const { WorkOrderCode } = this.form;
      const params = {
        TeamName: WorkOrderCode || "", // 班组名称
        rows: this.pageSize,
        page: this.currentPage,
      };
      console.log(params);
      const res = await getTeamInfoList(params);
      if (res.status === 0) {
        this.$refs.dataTableRef.tableData = res.rows || [];
        console.log(this.$refs.dataTableRef.tableData);
        this.totalPage = res.total || 0;
      } else {
        this.$refs.dataTableRef.tableData = [];
        this.totalPage = 0;
        this.$message.error(res.msg || "查询失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
  async addChange(title) {
    this.addTitle = title;
    this.$nextTick(() => {
      this.$refs.teamManagementInfoRef.clearValidate();
      this.$refs.teamManagementInfoRef2.clearValidate();
    });
    this.$refs.addDialogComRef.dialogVisible = true;
    this.$refs.addDialogComRef.loading = true;
    // 获取生产人员
    try{
      const params ={
        page: 1,
        rows: 1000,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify([])
      }
      const res = await getEmployeesInfo(params)
      if(res.status === 0) {
        this.employeeOption = [ ...res.rows ] || []
      }
      this.$refs.addDialogComRef.loading = false;
    } catch (err) {
      this.$message.error(err.msg || "查询失败");
      this.$refs.addDialogComRef.loading = false;
    }
  },
  // 增加行数据
  addRow() {
    let index = this.teamMembers.length;
    this.teamMembers.push({
      key: index,
      employeesId: ""
    });
  },
  // 删除行数据
  handleDeleteRow(row) {
    let data = this.teamMembers;
    for (var i = 0; i < data.length; i++) {
      if (data[i].key == row.key) {
        data.splice(i, 1);
      }
    }
  },
  // 重置table行数据
  resetForm() {
    this.employeeOption = [];
    let data = this.teamMembers;
    // 清空数据
    for (var i = 0; i < data.length; i++) {
      data[i].employeesId = ""
    }
    // 如果全部删除 再初始化一条数据
    if(this.teamMembers.length === 0) {
      this.teamMembers = [{key: 0, employeesId: null}]
    }
    // 保留一条
    this.teamMembers.splice(1)
  },
  // 清空弹框的数据
  closeChange() {
    this.teamManagementInfo = {};
    this.resetForm();
    this.$refs.teamManagementInfoRef.clearValidate();
    this.$refs.teamManagementInfoRef2.clearValidate();
  },
  // 确认提交操作
  confirmChange() {
    this.$refs.teamManagementInfoRef.validate((valid) => {
      if (valid) {
        if(this.teamMembers.length === 0) {
          this.$message.error('至少添加一行数据')
          return
        }
        this.$refs.teamManagementInfoRef2.validate(async (valid2) => {
          if (valid2) {
            try {
              this.$refs.addDialogComRef.loading = true;
              const {
                teamCode,
                teamName,
                remark,
              } = this.teamManagementInfo;
              const params = {
                teamCode: teamCode, // 班组编码
                teamName: teamName, // 班组名称
                teamMembers: this.teamMembers.map((item) => {
                  return {
                    employeesId: item.employeesId,
                  };
                }), // 人员集合array
                remark: remark, // 描述
              };
              const isAdd =
                !this.teamManagementInfo.teamId;
              const text = isAdd ? "添加" : "修改";
              if (!isAdd) {
                params.teamId =
                  this.teamManagementInfo.teamId;
              }
              const apiName = isAdd
                ? addTeam
                : updateTeam;
              const result = await apiName(params);
              if (result.ok) {
                this.$message.success(text + "成功");
                this.$refs.addDialogComRef.dialogVisible = false;
                if(isAdd) this.currentPage = 1
                this.closeChange();
                this.getTableData();
              } else {
                this.$message.error((result.err && result.err.msg) || (text + "失败"));
              }
              this.$refs.addDialogComRef.loading = false;
            } catch (err) {
              this.$refs.addDialogComRef.loading = false;
              console.error(text + "数据异常:", err);
            }
          }
        });
      }
    });
  },
  detailChange(val) {
    this.updateChange(val);
  },
  updateChange(val) {
    this.teamManagementInfo = JSON.parse(JSON.stringify(val));
    this.teamMembers = this.teamManagementInfo.teamMemberInfos.map((item, index)=> {
      return {
        key: index,
        employeesId: item.employeesId
      }
    })
    this.addChange('修改班组管理')
  },
  async deleteChange(val) {
    // delNum用于切换页码
    const oldCurrentPage = this.currentPage;
    const temp = Math.ceil(Math.max(this.totalPage - 1, 1) / this.pageSize);
    if (this.currentPage > temp) {
      this.currentPage = temp;
    }
    this.$refs.dataTableRef.tableLoading = true;
    try {
      const params = {
        id: val.teamId || "", // 质量检验方案id
      };
      const res = await deleteTeam(params);
      if (res.ok) {
        this.$message.success("删除成功");
        this.getTableData();
      } else {
        this.currentPage = oldCurrentPage;
        this.$message.error((res.err&&res.err.msg) || "删除失败");
      }
      this.$refs.dataTableRef.tableLoading = false;
    } catch (err) {
      this.currentPage = oldCurrentPage;
      this.$message.error((err.err&&err.err.msg) || "删除失败");
      this.$refs.dataTableRef.tableLoading = false;
    }
  },
};
